package org.example.imageservice.controller;


import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class VideoController {

    private final ResourceLoader resourceLoader;

    public VideoController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping("/getVideo")
    public List<String> getVideoUrls() throws IOException {
        List<String> videoUrls = new ArrayList<>();

        // 获取static/login-video文件夹的绝对路径
        Resource resource = resourceLoader.getResource("classpath:static/login-video/");
        File videoDir = resource.getFile();

        // 遍历文件夹中的所有文件，找到视频文件
        boolean foundOneVideo = false; // 设置标志位
        File[] files = videoDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (foundOneVideo) {
                    break; // 如果已经找到一个视频文件，就退出循环
                }
                if (file.isDirectory()) {
                    findVideos(file, videoUrls, foundOneVideo);
                } else {
                    String fileName = file.getName();
                    if (isVideoFile(fileName)) {
                        String videoUrl = "http://localhost:8086/login-video/" + fileName;
                        videoUrls.add(videoUrl);
                        foundOneVideo = true;
                    }
                }
            }
        }

        return videoUrls;
    }

    private void findVideos(File directory, List<String> videoUrls, boolean foundOneVideo) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (foundOneVideo) {
                    break; // 如果已经找到一个视频文件，就退出循环
                }
                if (file.isDirectory()) {
                    findVideos(file, videoUrls, foundOneVideo);
                } else {
                    String fileName = file.getName();
                    if (isVideoFile(fileName)) {
                        String videoUrl = "http://localhost:8086/login-video/" + fileName;
                        videoUrls.add(videoUrl);
                        foundOneVideo = true;
                    }
                }
            }
        }
    }

    private boolean isVideoFile(String fileName) {
        return fileName.endsWith(".mp4") || fileName.endsWith(".avi") || fileName.endsWith(".mov");
    }
}
